package com.jiunuan.live.api.service.impl;

import com.jiunuan.live.api.service.ImService;
import com.jiunuan.live.api.vo.resp.ImConfigVO;
import com.jiunuan.live.im.constants.AppIdEnum;
import com.jiunuan.live.im.interfaces.ImTokenRpc;
import com.jiunuan.live.web.starter.context.JiuNuanRequestContext;
import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.cloud.client.ServiceInstance;

import java.util.Collections;
import java.util.List;

/**
 * @Author: JiuNuan
 * @CreateTime: 2024-08-26 16:29
 * @Description:
 */
@Service
public class ImServiceImpl implements ImService {
    @DubboReference
    private ImTokenRpc imTokenRpc;
    @Resource
    private DiscoveryClient discoveryClient;
    /**
     * 获取im配置
     * 这里是通过DiscoveryClient获取Nacos中的注册信息，
     * 我们还可以通过在ImCoreServer中写一个rpc方法，
     * 和构建Router功能是一样，获取我们在启动参数中的添加的DUBBO注册ip
     * @return
     */
    @Override
    public ImConfigVO getImConfig() {
        ImConfigVO imConfigVO = new ImConfigVO();
        imConfigVO.setToken(imTokenRpc.createImLoginToken(JiuNuanRequestContext.getUserId(), AppIdEnum.JIUNUAN_LIVE_BIZ.getCode()));
        buildImServerAddress(imConfigVO);
        return imConfigVO;
    }

    /**
     * 构建im服务器地址
     * @param imConfigVO
     */
    private void buildImServerAddress(ImConfigVO imConfigVO) {
        // 获取到在Nacos中注册的对应服务名的实例集合
        List<ServiceInstance> serverInstanceList = discoveryClient.getInstances("jiunuan-live-im-core-server");
        // 打乱集合顺序
        Collections.shuffle(serverInstanceList);
        ServiceInstance serviceInstance = serverInstanceList.get(0);
        imConfigVO.setTcpImServerAddress(serviceInstance.getHost() + ":8025");
        imConfigVO.setWsImServerAddress(serviceInstance.getHost() + ":8026");
    }
}
